package util

import (
	"database/sql/driver"
	"fmt"
	"time"
)

type HTime struct {
	time.Time
}

var (
	NormDatetimePattern = "2006-01-02 15:04:05"

	Year   = "YEAR"
	Month  = "MONTH"
	Day    = "DAY"
	Hour   = "HOUR"
	Minute = "MINUTE"
	Second = "SECOND"
)

// Between 判断时间的差值
func Between(beginDate time.Time, endDate time.Time, DateField string) int64 {
	beginDateUnix := beginDate.Unix()
	endDateUnix := endDate.Unix()
	diff := beginDateUnix - endDateUnix
	println(beginDateUnix, endDateUnix, diff)

	if DateField == Second {
		return diff
	}

	if DateField == Minute {
		return diff / 60
	}

	if DateField == Hour {
		return diff / 60 / 60
	}

	if DateField == Day {
		return diff / 60 / 60 / 24
	}

	if DateField == Month {
		return diff / 60 / 60 / 24 / 30
	}

	//if DateField == Year {
	return diff / 60 / 60 / 24 / 30 / 12
	//}

}

// ParseDate 时间格式化
func ParseDate(dateStr string) time.Time {

	// 加载时区
	loc, err := time.LoadLocation("Asia/Shanghai")
	if err != nil {
		fmt.Println(err)
	}
	// 按照指定时区和指定格式解析字符串时间
	timeObj, err := time.ParseInLocation(NormDatetimePattern, dateStr, loc)
	return timeObj
}

func DateTimeBefore() bool {
	time1 := time.Now() // 假设是我们的某个时间点
	time2 := time.Now() // 假设是我们的某个时间点
	return time2.Before(time1)
}

// CurrentTime 获取当前时间
func CurrentTime() time.Time {
	return time.Now()
}

// Offset 时间偏移
func Offset(dateTime time.Time, DateField string, offset int) time.Time {
	if DateField == Year {
		return dateTime.AddDate(offset, 0, 0)
	}
	if DateField == Month {
		return dateTime.AddDate(0, offset, 0)
	}
	if DateField == Day {
		return dateTime.AddDate(0, 0, offset)
	}
	return dateTime
}

// DateTimeFormat 时间格式化
func DateTimeFormat(dateTime time.Time) string {
	return dateTime.Format(NormDatetimePattern)
}

// Now 获取当前时间标准格式
func Now() string {
	return time.Now().Format(NormDatetimePattern)
}

func DateTimeStr() string {
	now := time.Now() //获取当前时间
	fmt.Printf("current time:%v\n", now)

	year := now.Year()     //年
	month := now.Month()   //月
	day := now.Day()       //日
	hour := now.Hour()     //小时
	minute := now.Minute() //分钟
	second := now.Second() //秒
	sprintf := fmt.Sprintf("%d-%02d-%02d %02d:%02d:%02d", year, month, day, hour, minute, second)
	return sprintf
}

func (t HTime) MarshalJSON() ([]byte, error) {
	formatted := fmt.Sprintf("\"%s\"", t.Format(NormDatetimePattern))
	return []byte(formatted), nil
}

func (t *HTime) UnmarshalJSON(data []byte) (err error) {
	now, err := time.ParseInLocation(`"`+NormDatetimePattern+`"`, string(data), time.Local)
	*t = HTime{Time: now}
	return
}

func (t HTime) Value() (driver.Value, error) {
	var zeroTime time.Time
	if t.Time.UnixNano() == zeroTime.UnixNano() {
		return nil, nil
	}
	return t.Time, nil
}

func (t *HTime) Scan(v interface{}) error {
	value, ok := v.(time.Time)
	if ok {
		*t = HTime{Time: value}
		return nil
	}
	return fmt.Errorf("can not convert %v to timestamp", v)
}
